const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config();

// Notion API配置
const NOTION_TOKEN = process.env.NOTION_TOKEN;
const LOG_DATABASE_ID = process.env.LOG_DATABASE_ID;

// 检查必要配置
if (!NOTION_TOKEN || !LOG_DATABASE_ID) {
  console.error('Missing required environment variables: NOTION_TOKEN or LOG_DATABASE_ID');
  process.exit(1);
}

// 配置日志级别
const LOG_LEVEL = process.env.LOG_LEVEL || 'info';
const logLevels = {
  error: 0,
  warn: 1,
  info: 2,
  debug: 3
};

/**
 * 记录日志的辅助函数
 * @param {string} level - 日志级别
 * @param {string} message - 日志消息
 * @param {any} data - 附加数据
 */
function log(level, message, data = null) {
  // 只有在配置的日志级别允许时才输出日志
  if (logLevels[level] <= logLevels[LOG_LEVEL]) {
    const timestamp = new Date().toISOString();
    const logMessage = `${timestamp} [${level.toUpperCase()}] ${message}`;
    
    if (level === 'error') {
      console.error(logMessage);
    } else if (level === 'warn') {
      console.warn(logMessage);
    } else {
      console.log(logMessage);
    }
    
    if (data) {
      console.log(JSON.stringify(data, null, 2));
    }
  }
}

// Notion API客户端
const notion = require('@notionhq/client');
const client = new notion.Client({ auth: NOTION_TOKEN });

/**
 * 解析日志文件
 * @param {string} filePath - 日志文件路径
 * @returns {Array} 解析后的日志条目数组
 */
function parseLogFile(filePath) {
  try {
    log('info', `Reading log file: ${filePath}`);
    const content = fs.readFileSync(filePath, 'utf8');
    const lines = content.split('\n');
    const logs = [];
    
    lines.forEach((line, index) => {
      if (line.trim()) {
        try {
          // 尝试解析JSON格式的日志
          const logEntry = JSON.parse(line);
          logs.push(logEntry);
        } catch (jsonParseError) {
          // 处理非JSON格式的日志行
          const parsedLog = parseNonJsonLogLine(line);
          if (parsedLog) {
            logs.push(parsedLog);
          }
        }
      }
    });
    
    log('info', `Parsed ${logs.length} log entries from ${filePath}`);
    return logs;
  } catch (error) {
    log('error', `Error reading log file ${filePath}: ${error.message}`);
    return [];
  }
}

/**
 * 解析非JSON格式的日志行
 * @param {string} line - 日志行
 * @returns {Object|null} 解析后的日志对象或null
 */
function parseNonJsonLogLine(line) {
  // 匹配 Winston 格式的日志: 2025-11-25T08:22:56.728Z [Spiritual Insight] info: 这是info级别的日志
  const winstonRegex = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\s+\[(.*?)\]\s+(\w+):\s*(.+)$/;
  const match = line.match(winstonRegex);
  
  if (match) {
    const timestamp = match[1];
    const component = match[2];
    const level = match[3];
    let message = match[4].trim();
    let meta = {};
    
    // 如果消息以 { 开头，可能是元数据
    if (message.endsWith('{')) {
      // 尝试读取下一行作为元数据
      // 注意：由于我们是逐行处理的，这里只能做简单的处理
      try {
        // 简单处理，实际应用中可能需要更复杂的逻辑
        meta = { raw: message };
        message = message.replace(/\s*{$/, '').trim() || 'No message';
      } catch (e) {
        // 如果解析失败，保持原样
      }
    }
    
    return {
      timestamp,
      component,
      level,
      message,
      meta
    };
  }
  
  // 如果不匹配任何已知格式，创建一个基本的日志条目
  return {
    timestamp: new Date().toISOString(),
    level: 'info',
    message: line,
    meta: {}
  };
}

/**
 * 将日志条目同步到Notion数据库
 * @param {Array} logs - 日志条目数组
 * @param {string} sourceFile - 日志源文件名
 */
async function syncLogsToNotion(logs, sourceFile) {
  log('info', `Syncing ${logs.length} log entries from ${sourceFile} to Notion...`);
  let successCount = 0;
  let errorCount = 0;
  
  for (const [index, logEntry] of logs.entries()) {
    try {
      // 准备Notion页面属性
      const properties = {
        'Timestamp': {
          date: {
            start: logEntry.timestamp || new Date().toISOString()
          }
        },
        'Level': {
          select: {
            name: logEntry.level || 'info'
          }
        },
        'Message': {
          title: [
            {
              text: {
                content: logEntry.message || 'No message'
              }
            }
          ]
        },
        'Component': {
          rich_text: [
            {
              text: {
                content: logEntry.component || 'unknown'
              }
            }
          ]
        },
        'Environment': {
          select: {
            name: (logEntry.meta && logEntry.meta.environment) || 'unknown'
          }
        },
        'Source File': {
          rich_text: [
            {
              text: {
                content: sourceFile
              }
            }
          ]
        }
      };
      
      // 添加元数据（如果存在）
      if (logEntry.meta && Object.keys(logEntry.meta).length > 0) {
        properties.Metadata = {
          rich_text: [
            {
              text: {
                content: JSON.stringify(logEntry.meta)
              }
            }
          ]
        };
      }
      
      await client.pages.create({
        parent: { database_id: LOG_DATABASE_ID },
        properties
      });
      
      successCount++;
      log('debug', `Successfully synced log entry ${index + 1}/${logs.length}: ${logEntry.message || 'No message'}`);
    } catch (error) {
      errorCount++;
      log('error', `Error syncing log entry ${index + 1}/${logs.length} to Notion: ${error.message}`, {
        logEntry,
        sourceFile
      });
    }
  }
  
  log('info', `Finished syncing logs from ${sourceFile}. Success: ${successCount}, Errors: ${errorCount}`);
  return { successCount, errorCount };
}

/**
 * 主函数
 */
async function main() {
  const logsDir = path.join(__dirname, '..', 'logs');
  const logFiles = ['development.log', 'error.log', 'http.log'];
  
  log('info', 'Starting log sync process...');
  let totalSuccess = 0;
  let totalErrors = 0;
  
  for (const file of logFiles) {
    const filePath = path.join(logsDir, file);
    
    if (fs.existsSync(filePath)) {
      log('info', `Processing ${file}...`);
      const logs = parseLogFile(filePath);
      
      if (logs.length > 0) {
        const { successCount, errorCount } = await syncLogsToNotion(logs, file);
        totalSuccess += successCount;
        totalErrors += errorCount;
      } else {
        log('info', `No logs found in ${file}`);
      }
    } else {
      log('warn', `Log file ${file} not found`);
    }
  }
  
  log('info', 'Log sync process completed.', {
    totalSuccess,
    totalErrors
  });
  
  // 如果有错误，退出码为1
  if (totalErrors > 0) {
    process.exit(1);
  }
}

// 执行主函数
main().catch(error => {
  console.error('Fatal error in log sync process:', error);
  process.exit(1);
});